package com.ruoyi.app.common.exception;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.ResultData;
import com.ruoyi.common.exception.BusinessException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.profiles.active}")
    private String env;

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public AjaxResult handleBusinessException(BusinessException e) {
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
//        if (env.equals("dev")) {
            String msg = e.getMessage();
//            if (msg == null || msg.equals("")) {
//                msg = "網絡連接超時";
//            }
            e.printStackTrace();
            return AjaxResult.error(msg);
//        } else {
//            return AjaxResult.error("網絡連接超時");
//        }
    }

    // 捕捉未授权异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResultData handleUnauthorizedException() {
        return new ResultData(401, "请先授权登录");
    }
}